/*
 * commons is a based project implemented
 * Copyright (C) 2024 Jasmine
 */
package com.commons.ip.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Objects;
import java.util.function.Function;
import java.util.regex.Pattern;

import org.springframework.lang.Nullable;

import com.commons.core.constant.StringPool;
import com.commons.core.utils.ApplicationContextHolder;
import com.commons.ip.domain.IpInfo;
import com.commons.ip.service.Ip2regionSearcher;

import jakarta.servlet.http.HttpServletRequest;

/**
 * ip 工具
 * 
 * @description
 * @version 1.0
 * @author Jasmine
 * @since 2024-01-08 10:39:39
 * @see IpUtil
 */
public class IpUtil {

    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST_IP = "127.0.0.1";
    // 客户端与服务器同为一台机器，获取的 ip 有时候是 ipv6 格式
    private static final String LOCALHOST_IPV6 = "0:0:0:0:0:0:0:1";

    private static final Pattern SPLIT_PATTERN = Pattern.compile("\\|");
    private static final Pattern DOT_PATTERN = Pattern.compile("\\.");
    private static final Pattern T_PATTERN = Pattern.compile("\\t");

    private static final Ip2regionSearcher ip2regionSearcher =
        ApplicationContextHolder.getBean(Ip2regionSearcher.class);

    /**
     * 查询 IP 归属地（本地库解析）
     *
     * @param request 请求
     * @return IP 归属地
     */
    public static String getAddress(HttpServletRequest request) {
        String remoteIP = getRemoteIP(request);
        // 返回 中国 安徽省 芜湖市 电信
        return getAddress(remoteIP);
    }

    /**
     * 查询 IP 归属地（本地库解析）
     *
     * @param ip IP 地址
     * @return IP 归属地
     */
    public static String getAddress(String ip) {
        if (internalIp(ip)) {
            return "内网IP";
        }
        // 返回 中国 安徽省 芜湖市 电信
        return ip2regionSearcher.getAddressAndIsp(ip);
    }

    public static String getRemoteIP(HttpServletRequest request) {
        if (request == null) {
            return UNKNOWN;
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (LOCALHOST_IP.equalsIgnoreCase(ip) || LOCALHOST_IPV6.equalsIgnoreCase(ip)) {
                // 根据网卡取本机配置的 IP
                InetAddress iNet = null;
                try {
                    iNet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                if (iNet != null)
                    ip = iNet.getHostAddress();
            }
        }

        // 多次反向代理后会有多个IP值，第一个为真实IP。
        if (ip != null && ip.length() > 15) {
            int index = ip.indexOf(StringPool.COMMA);
            if (index > 0) {
                ip = ip.substring(0, index);
            }
        }
        return LOCALHOST_IPV6.equals(ip) ? LOCALHOST_IP : ip;
    }

    /**
     * 是否为内网 IPv4
     *
     * @param ip IP 地址
     * @return 是否为内网 IP
     */
    public static boolean internalIp(String ip) {
        byte[] adder = textToNumericFormatV4(ip);
        return internalIp(adder) || "127.0.0.1".equals(ip);
    }

    private static boolean internalIp(byte[] addr) {
        if (Objects.isNull(addr) || addr.length < 2) {
            return true;
        }
        final byte b0 = addr[0];
        final byte b1 = addr[1];
        // 10.x.x.x/8
        final byte SECTION_1 = 0x0A;
        // 172.16.x.x/12
        final byte SECTION_2 = (byte)0xAC;
        final byte SECTION_3 = (byte)0x10;
        final byte SECTION_4 = (byte)0x1F;
        // 192.168.x.x/16
        final byte SECTION_5 = (byte)0xC0;
        final byte SECTION_6 = (byte)0xA8;
        switch (b0) {
            case SECTION_1:
                return true;
            case SECTION_2:
                if (b1 >= SECTION_3 && b1 <= SECTION_4) {
                    return true;
                }
            case SECTION_5:
                switch (b1) {
                    case SECTION_6:
                        return true;
                }
            default:
                return false;
        }
    }

    /**
     * 获取 ip v4 part
     *
     * @return 是否 ipv4
     */
    public static String[] getIpV4Part(String ip) {
        return DOT_PATTERN.split(ip);
    }

    /**
     * 将 DataBlock 转化为 IpInfo
     *
     * @param region region
     * @return IpInfo
     */
    @Nullable
    public static IpInfo toIpInfo(@Nullable String region) {
        if (region == null) {
            return null;
        }
        IpInfo ipInfo = new IpInfo();
        String[] splitInfoArr = SPLIT_PATTERN.split(region);
        // 补齐5位
        if (splitInfoArr.length < 5) {
            splitInfoArr = Arrays.copyOf(splitInfoArr, 5);
        }
        ipInfo.setCountry(filterZero(splitInfoArr[0]));
        ipInfo.setRegion(filterZero(splitInfoArr[1]));
        ipInfo.setProvince(filterZero(splitInfoArr[2]));
        ipInfo.setCity(filterZero(splitInfoArr[3]));
        ipInfo.setIsp(filterZero(splitInfoArr[4]));
        return ipInfo;
    }

    /**
     * 将 ipv6 地区转化为 IpInfo
     *
     * @param ipRecord ipRecord
     * @return IpInfo
     */
    @Nullable
    public static IpInfo toIpV6Info(String[] ipRecord) {
        IpInfo ipInfo = new IpInfo();
        String info1 = ipRecord[0];
        String[] splitInfoArr = T_PATTERN.split(info1);
        // 补齐5位
        if (splitInfoArr.length < 4) {
            splitInfoArr = Arrays.copyOf(splitInfoArr, 4);
        }
        ipInfo.setCountry(splitInfoArr[0]);
        ipInfo.setProvince(splitInfoArr[1]);
        ipInfo.setCity(splitInfoArr[2]);
        ipInfo.setRegion(splitInfoArr[3]);
        ipInfo.setIsp(ipRecord[1]);
        return ipInfo;
    }

    /**
     * 数据过滤，因为 ip2Region 采用 0 填充的没有数据的字段
     *
     * @param info info
     * @return info
     */
    @Nullable
    private static String filterZero(@Nullable String info) {
        // null 或 0 返回 null
        if (info == null || "0".equals(info)) {
            return null;
        }
        return info;
    }

    /**
     * 读取 IpInfo
     *
     * @param ipInfo IpInfo
     * @param function Function
     * @return info
     */
    @Nullable
    public static String readInfo(@Nullable IpInfo ipInfo, Function<IpInfo, String> function) {
        if (ipInfo == null) {
            return null;
        }
        return function.apply(ipInfo);
    }

    /**
     * 将IPv4地址转换成字节
     *
     * @param text IPv4地址
     * @return byte 字节
     */
    public static byte[] textToNumericFormatV4(String text) {
        if (text.length() == 0) {
            return null;
        }

        byte[] bytes = new byte[4];
        String[] elements = text.split("\\.", -1);
        try {
            long l;
            int i;
            switch (elements.length) {
                case 1:
                    l = Long.parseLong(elements[0]);
                    if ((l < 0L) || (l > 4294967295L)) {
                        return null;
                    }
                    bytes[0] = (byte)(int)(l >> 24 & 0xFF);
                    bytes[1] = (byte)(int)((l & 0xFFFFFF) >> 16 & 0xFF);
                    bytes[2] = (byte)(int)((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte)(int)(l & 0xFF);
                    break;
                case 2:
                    l = Integer.parseInt(elements[0]);
                    if ((l < 0L) || (l > 255L)) {
                        return null;
                    }
                    bytes[0] = (byte)(int)(l & 0xFF);
                    l = Integer.parseInt(elements[1]);
                    if ((l < 0L) || (l > 16777215L)) {
                        return null;
                    }
                    bytes[1] = (byte)(int)(l >> 16 & 0xFF);
                    bytes[2] = (byte)(int)((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte)(int)(l & 0xFF);
                    break;
                case 3:
                    for (i = 0; i < 2; ++i) {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > 255L)) {
                            return null;
                        }
                        bytes[i] = (byte)(int)(l & 0xFF);
                    }
                    l = Integer.parseInt(elements[2]);
                    if ((l < 0L) || (l > 65535L)) {
                        return null;
                    }
                    bytes[2] = (byte)(int)(l >> 8 & 0xFF);
                    bytes[3] = (byte)(int)(l & 0xFF);
                    break;
                case 4:
                    for (i = 0; i < 4; ++i) {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > 255L)) {
                            return null;
                        }
                        bytes[i] = (byte)(int)(l & 0xFF);
                    }
                    break;
                default:
                    return null;
            }
        } catch (NumberFormatException e) {
            return null;
        }
        return bytes;
    }

}
